package com.wannengbang.cloudleader.homepage;


import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.stx.xhb.xbanner.XBanner;
import com.stx.xhb.xbanner.transformers.Transformer;
import com.wannengbang.cloudleader.R;
import com.wannengbang.cloudleader.base.BaseFragment;
import com.wannengbang.cloudleader.base.DataCallBack;
import com.wannengbang.cloudleader.bean.AgentLevelBean;
import com.wannengbang.cloudleader.bean.BannerListBean;
import com.wannengbang.cloudleader.bean.DailyStatisticsBean;
import com.wannengbang.cloudleader.bean.ExpiredCountBean;
import com.wannengbang.cloudleader.bean.RevenueListBean;
import com.wannengbang.cloudleader.bean.UnReadMsgBean;
import com.wannengbang.cloudleader.bean.UserInfoBean;
import com.wannengbang.cloudleader.event.UpDateNameEvent;
import com.wannengbang.cloudleader.homepage.model.HomePageModelImpl;
import com.wannengbang.cloudleader.homepage.model.IHomePageModel;
import com.wannengbang.cloudleader.mine.AddressListActivity;
import com.wannengbang.cloudleader.mine.OrderClassifyActivity;
import com.wannengbang.cloudleader.mine.ProductClassifyActivity;
import com.wannengbang.cloudleader.mine.model.MineModelImpl;
import com.wannengbang.cloudleader.utils.DateTimeUtil;
import com.wannengbang.cloudleader.utils.GlideUtils;
import com.wannengbang.cloudleader.utils.NumberFormatUtils;
import com.wannengbang.cloudleader.utils.SPManager;
import com.wannengbang.cloudleader.widget.CommonNoTitleDialog;
import com.wannengbang.cloudleader.widget.RoundImageView;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 首页
 */
public class HomePageFragment extends BaseFragment {
    @BindView(R.id.tv_order_fee_sum)
    TextView tvOrderFeeSum;
    @BindView(R.id.ll_add_merchant)
    LinearLayout llAddMerchant;
    @BindView(R.id.tv_withdraw)
    LinearLayout tvWithdraw;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.ll_event_7)
    LinearLayout llEvent7;
    @BindView(R.id.tv_today_money)
    TextView tvTodayMoney;
    @BindView(R.id.ll_event_1)
    LinearLayout llEvent1;
    @BindView(R.id.ll_event_3)
    LinearLayout llEvent3;
    @BindView(R.id.ll_event_8)
    LinearLayout llEvent8;
    @BindView(R.id.ll_event_4)
    LinearLayout llEvent4;
    @BindView(R.id.ll_event_5)
    LinearLayout llEvent5;
    @BindView(R.id.ll_event_11)
    LinearLayout llEvent11;
    @BindView(R.id.tv_start_count)
    TextView tvStartCount;
    @BindView(R.id.ll_my_order)
    LinearLayout llMyOrder;
    @BindView(R.id.ll_my_address)
    LinearLayout llMyAddress;
    @BindView(R.id.ll_ranking_list)
    LinearLayout llRankingList;
    @BindView(R.id.ll_share_bonus)
    LinearLayout llShareBonus;
    @BindView(R.id.xbanner)
    XBanner xbanner;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.ll_share_level)
    LinearLayout llShareLevel;
    @BindView(R.id.tv_msg_num)
    TextView tvMsgNum;
    @BindView(R.id.ll_msg_num)
    RelativeLayout llMsgNum;
    @BindView(R.id.tv_remind)
    TextView tvRemind;
    @BindView(R.id.ll_merchant_manage)
    LinearLayout llMerchantManage;
    @BindView(R.id.ll_remind)
    LinearLayout llRemind;
    @BindView(R.id.ll_machines_plate)
    LinearLayout llMachinesPlate;
    @BindView(R.id.ll_compliance_progress)
    LinearLayout ll_compliance_progress;
    private IHomePageModel homePageModel;
    private CommonNoTitleDialog.Builder dialogBuild;
    private int child_agent_id;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home_page, container, false);
        ButterKnife.bind(this, view);
        registerEventBus();
        initView();
        return view;
    }

    public void initView() {
        homePageModel = new HomePageModelImpl();
        requestData();
        requestUserInfo();
        requestAdIndex();
    }

    @Subscribe
    public void onUpDateNameEvent(UpDateNameEvent event) {
        UserInfoBean userInfoBean = new Gson().fromJson(SPManager.getInstance().getUserInfoJson(), UserInfoBean.class);
        tvName.setText(userInfoBean.getData().getName());
    }

    @Override
    public void onResume() {
        super.onResume();
        requestData();
        requestUserInfo();
        requestAgentGetLevel();
        requestUnReadMsgNum();
        requestToBeExpiredCount();
        UserInfoBean userInfoBean = new Gson().fromJson(SPManager.getInstance().getUserInfoJson(), UserInfoBean.class);
        if (userInfoBean != null) {
            tvName.setText(userInfoBean.getData().getName());
            child_agent_id = userInfoBean.getData().getId();
        }
    }

    public void requestAdIndex() {
        homePageModel.requestAdIndex(new DataCallBack<BannerListBean>() {
            @Override
            public void onSuccessful(BannerListBean bean) {
                if (bean.getData().getItemList() != null && bean.getData().getItemList().size() > 0) {
                    xbanner.setVisibility(View.GONE);
                    xbanner.setPageTransformer(Transformer.Default);
                    xbanner.setData(R.layout.item_banner_conner_iv, bean.getData().getItemList(), null);
                    xbanner.loadImage(new XBanner.XBannerAdapter() {
                        @Override
                        public void loadBanner(XBanner banner, Object model, View view, int position) {
                            RoundImageView view1 = (RoundImageView) view;
                            GlideUtils.loadImage(mActivity, view1, bean.getData().getItemList().get(position).getPic());
                        }
                    });

                    //1标记隐藏
                    UserInfoBean userInfoBean = new Gson().fromJson(SPManager.getInstance().getUserInfoJson(), UserInfoBean.class);
                    if (userInfoBean != null) {
                        if ("17329409714".equals(userInfoBean.getData().getMobile()) || "13403854628".equals(userInfoBean.getData().getMobile())) {
                            xbanner.setVisibility(View.GONE);
                        }
                    }

                } else {
                    xbanner.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }


    public void requestAgentGetLevel() {
        homePageModel.requestAgentGetLevel(new DataCallBack<AgentLevelBean>() {
            @Override
            public void onSuccessful(AgentLevelBean bean) {
                tvStartCount.setText(bean.getData().getLevel());
                tvEndTime.setText("特权有效期至：" + bean.getData().getEnd_date());
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    private boolean isViewCreated; // 界面是否已创建完成
    private boolean isVisibleToUser; // 是否对用户可见

    /**
     * Fragment 创建期间setUserVisibleHint()方法是在onActivityCreated()之前被调用
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        tryLoadData();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewCreated = true;
        tryLoadData();
    }

    public void tryLoadData() {
        if (isViewCreated && isVisibleToUser) {
            requestData();
            requestAgentGetLevel();
            requestUnReadMsgNum();
            requestToBeExpiredCount();
        }
    }

    public void requestUnReadMsgNum() {
        homePageModel.requestUnReadMsgNum(new DataCallBack<UnReadMsgBean>() {
            @Override
            public void onSuccessful(UnReadMsgBean bean) {
                int unreadMsgNum = bean.getData().getPer_unread() + bean.getData().getSys_unread();
                if (unreadMsgNum > 0) {
                    llMsgNum.setVisibility(View.VISIBLE);
                    if (unreadMsgNum > 99) {
                        tvMsgNum.setText("99+");
                    } else {
                        tvMsgNum.setText(String.valueOf(unreadMsgNum));
                    }
                } else {
                    llMsgNum.setVisibility(View.GONE);
                    tvMsgNum.setText(String.valueOf(0));
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    /**
     * 用户信息
     */
    public void requestUserInfo() {
        new MineModelImpl().requestMine(new DataCallBack<UserInfoBean>() {
            @Override
            public void onSuccessful(UserInfoBean bean) {
                SPManager.getInstance().saveUserInfoJson(new Gson().toJson(bean));
                tvName.setText(bean.getData().getName());
                child_agent_id = bean.getData().getId();
                //1标记隐藏
                if ("17329409714".equals(bean.getData().getMobile()) || "13403854628".equals(bean.getData().getMobile())) {
                    llAddMerchant.setVisibility(View.GONE);
                    xbanner.setVisibility(View.GONE);
                    llMachinesPlate.setVisibility(View.GONE);
                } else {
                    llAddMerchant.setVisibility(View.VISIBLE);
                    xbanner.setVisibility(View.GONE);
                    llMachinesPlate.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    /**
     * 首页提醒未激活的机具数量不足xx天内的
     */
    public void requestToBeExpiredCount() {
        homePageModel.requestToBeExpiredCount(new DataCallBack<ExpiredCountBean>() {
            @Override
            public void onSuccessful(ExpiredCountBean bean) {
                if (isDestroy()) {
                    return;
                }
                if (bean.getData().getCount() > 0) {
                    tvRemind.setText("还有" + bean.getData().getCount() + "台机具剩余激活时间不足" + bean.getData().getPeriod() + "天");
                    llRemind.setVisibility(View.VISIBLE);
                } else {
                    llRemind.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    /**
     * 今日数据
     */
    public void requestData() {
        homePageModel.requestDailyStatistics(DateTimeUtil.getToDayDate(), new DataCallBack<DailyStatisticsBean>() {
            @Override
            public void onSuccessful(DailyStatisticsBean bean) {
                String orderFeeSum = NumberFormatUtils.formatTwoDecimal(Double.parseDouble(bean.getData().getOrder_fee_sum()) / 100);
                tvOrderFeeSum.setText(orderFeeSum);
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    public List<RevenueListBean.DataBean> dataBeans = new ArrayList<>();

    @OnClick({R.id.ll_add_merchant, R.id.tv_withdraw, R.id.ll_event_11,
            R.id.ll_event_1, R.id.ll_event_3, R.id.ll_event_4, R.id.ll_event_5,
            R.id.ll_event_7, R.id.ll_event_8, R.id.tv_today_money, R.id.ll_my_address,
            R.id.ll_my_order, R.id.ll_ranking_list, R.id.ll_share_bonus, R.id.ll_share_level,
            R.id.ll_merchant_manage, R.id.ll_remind, R.id.ll_money, R.id.iv_home_award, R.id.ll_draw_red_envelopes, R.id.ll_maker_dividend, R.id.ll_operation_center,R.id.ll_compliance_progress})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_add_merchant:
                skipToActivity(ProductClassifyActivity.class);
                break;
            case R.id.tv_withdraw:
                UserInfoBean userInfoBean = new Gson().fromJson(SPManager.getInstance().getUserInfoJson(), UserInfoBean.class);
                if (TextUtils.isEmpty(userInfoBean.getData().getSettle_card_no())) {
                    dialogBuild = new CommonNoTitleDialog.Builder(mActivity);
                    dialogBuild.setMessage("请前往“实名认证”页面绑定银行卡后进行操作？");
                    dialogBuild.setPositiveButton("立即前往", v -> {
                        dialogBuild.dismiss();
                        skipToActivity(SettlementInfoActivity.class);
                    });
                    dialogBuild.setNegativeButton("取消", v -> dialogBuild.dismiss());
                    dialogBuild.setCancelable(false);
                    dialogBuild.show();
                } else {
                    skipToActivity(WithdrawActivity.class);
                }
                break;
            case R.id.ll_event_1:
                skipToActivity(AgentListActivity.class);
                break;
            case R.id.ll_event_3:
                skipToActivity(MachinesClassifyActivity.class);
//                Intent intent = new Intent(mActivity, MachinesDetailsActivity.class);
//                intent.putExtra("type", "1");
//                intent.putExtra("child_agent_id", child_agent_id + "");
//                intent.putExtra("agent_name", "");/index.php/agent/DirectorBonusesLog/toBe
///                 index.php/agent/MarketShareBonus/index
//                startActivity(intent);
                break;
            case R.id.ll_event_4:
                List<String> lists = new ArrayList<>();
                lists.add("全部&0");
                for (int i = 0; i < dataBeans.size(); i++) {
                    lists.add(dataBeans.get(i).getName() + "&" + dataBeans.get(i).getName());
                }
                Intent intents = new Intent(mActivity, IncomeNewActivity.class);
                intents.putExtra("cycleType", "all");
                intents.putExtra("param", "2018-01-01");
                intents.putExtra("relation_type", 0);
                intents.putExtra("coordinate", 0);
                intents.putExtra("relation_name", "全部");
                intents.putExtra("lists", new Gson().toJson(lists));
                startActivity(intents);
                break;
            case R.id.ll_event_5:
                skipToActivity(TransactionQueryActivity.class);
                break;
            case R.id.ll_event_7:
                skipToActivity(MessageCenterActivity.class);
                break;
            case R.id.ll_event_8:
                skipToActivity(SettlementInfoActivity.class);
                break;
            case R.id.tv_today_money:
                skipToActivity(TransactionQueryActivity.class);
                break;
            case R.id.ll_event_11:
                skipToActivity(ExchangeMachinesActivity.class);
                break;
            case R.id.ll_my_address:
                skipToActivity(AddressListActivity.class);
                break;
            case R.id.ll_my_order:
                skipToActivity(OrderClassifyActivity.class);
                break;
            case R.id.ll_ranking_list:
                skipToActivity(RankingListActivity.class);
                break;
            case R.id.ll_share_level:
                skipToActivity(ShareLevelActivity.class);
                break;
            case R.id.ll_merchant_manage:
                Intent intent = new Intent(mActivity, MerchantListActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_remind:
                intent = new Intent(mActivity, MachinesDetailsActivity.class);
                intent.putExtra("type", "1");
                intent.putExtra("child_agent_id", child_agent_id + "");
                intent.putExtra("agent_name", "");
                intent.putExtra("is_send", "1");
                startActivity(intent);
                break;
            case R.id.ll_money:
//                intent = new Intent(mActivity, MyIntegralActivity.class);
//                startActivity(intent);
                break;
            case R.id.iv_home_award:
                intent = new Intent(mActivity, DrawRedEnvelopesActivity.class);
                startActivity(intent);
                break;

            case R.id.ll_draw_red_envelopes:
                intent = new Intent(mActivity, BountyListActivity.class);
                startActivity(intent);
                break;

            case R.id.ll_share_bonus:
//               1 董事 2 红包版运营中心分红 3创客
                intent = new Intent(mActivity, ShareBonusActivity.class);
                intent.putExtra("type", "1");
                startActivity(intent);
                break;
            case R.id.ll_maker_dividend:
                intent = new Intent(mActivity, ShareBonusActivity.class);
                intent.putExtra("type", "3");
                startActivity(intent);
                break;
            case R.id.ll_operation_center:
                intent = new Intent(mActivity, ShareBonusActivity.class);
                intent.putExtra("type", "2");
                startActivity(intent);
                break;
            case R.id.ll_compliance_progress:
                intent = new Intent(mActivity, ComplianceProgressActivity.class);
                startActivity(intent);

                break;
        }
    }
}
